/*-----------------------------------------------------------------------------
* @Description:     问卷管理列表
* @Version:         1.0.0
* @author:          sunwanlin (1124038074@qq.com)
* @date             2017.11.9
* ==NOTES:=============================================
* v1.0.0(2017.11.9):
     初始生成
* ---------------------------------------------------------------------------*/
$(function(){
    //**********************************以下是函数调用******************************************************************//

    //分页
    Pagination(1);
    //**********************************以下是事件绑定******************************************************************//

    /**
     * 列表点击搜索事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $(".J_search").click(function(){
        var
            form = $(".J_searchForm").serializeObject();
        Pagination(1, form);
    });
    /**
     * 分页
     */
    $('#pageLimit').bootstrapPaginator({
        //currentPage: 3,
        /*totalPages: $('.pageDataCount').val(),*/
        size: "small",
        bootstrapMajorVersion: 3,
        alignment: "right",
        numberOfPages: 5,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "<";
                case "next": return ">";
                case "last": return "末页";
                case "page": return page;
            }
        },
        onPageClicked: function (event, originalEvent, type, page) {
            var
                form = $(".J_searchForm").serializeObject();
            Pagination(page, form);  
        }
    });
    //全选事件
    $(".J_selectAll").click(function() {
        $('input[name="subCheck"]').prop("checked", this.checked);
    });
    //单选事件
    $(document).on('click', 'input[name="subCheck"]', function() {
        $(".J_selectAll").prop("checked", $('input[name="subCheck"]').length == $("input[name='subCheck']:checked").length ? true: false);
    });
    //批量删除事件
    $('.J_allDel').click(function(){
        delItem();
    });
    //**********************************以下是函数声明******************************************************************//
     
    /**
     * 批量删除
     */
    function delItem(){
        var 
            checkedList = [],
            checkedNum = $("input[name='subCheck']:checked").length,
            id,
            stateList =[];

        $("input[name='subCheck']:checked").each(function() {
            //tr的id进栈
            checkedList.push($(this).parents('tr').attr('data-id'));
            stateList.push($(this).parents('tr').attr('data-state'));
        }); 
        if(checkedNum == 0) { 
            Alert('提示信息', '请至少选择一项!');  
        }else {// 批量选择'
            if(stateList.indexOf('0')>=0){
                 Confirm('提示信息', '所删除的选项含进行中问卷，确认删除吗？',function(){
                    delAllTips()
                 });  
            }else{
                Confirm('提示信息', '确定删除所选问卷吗？', function(){
                    delAllTips()
                });  
            }
        }; 
        function delAllTips(){
            $.ajax({ 
                type: jQuery.url.QuestionnaireManagement.delList.type, 
                url: jQuery.url.QuestionnaireManagement.delList.url,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                data: {delitems:checkedList.toString()},
                dataType: "json",
                success: function(rs) { 
                    if(rs.code == 0){
                        $("[name ='subChk']:checkbox").attr("checked", false);
                        $(".J_allChk").prop("checked", false);
                        window.location.reload();
                    }else{
                        Alert('提示信息', '返回参数错误!'); 
                    }  
                },
                error: function (message) {
                     Alert('提示信息', '发送请求失败!'); 
                    $(".J_allChk").prop("checked", false);
                } 
            }); 
        }     
    };
    /**
     * 分页刷数据
     */
    function Pagination(page, extraData){

        var
            currentPage = page,            
            str = '',
            data = {
                pageNo: currentPage
            };
        jQuery.extend(data, extraData);

        $.ajax({
            type: jQuery.url.QuestionnaireManagement.questList.type,
            url: jQuery.url.QuestionnaireManagement.questList.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: data,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#J_template').empty();
                if( rs.code == 0){
                    $('#pageLimit').bootstrapPaginator({
                        totalPages: rs.pageDataCount
                    });
                    $.each(rs.list, function(index, item){
                        str += '<tr data-state="'+ item.state +'" data-id="'+ item.id +'">\
                                <td><input type="checkbox" name="subCheck"/></th>\
                                <td>'+ item.number +'</td>\
                                <td>'+ item.title +'</td>\
                                <td>'+ item.owner +'</td>\
                                <td>'+ item.count +'</td>\
                                <td>'+ item.state +'</td>\
                                <td>'+ item.startTime +'</td>\
                                <td>'+ item.endTime +'</td>\
                                <td>\
                                    <a href="/admin/quest/list/detail/'+ item.id +'" class="label-info"><i class="fa fa-book"></i>&nbsp;数据统计</a>\
                                </td>\
                            </tr>';

                    }); 
                    $('#J_template').append(str);
                }else{                
                    Alert('提示信息', '操作失败，返回参数错误');
                }
            },
            error: function (message) {
                Alert("提示信息", "请求发送失败。")
            }
        });
    }
    /**
     * 批量导出按钮
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    $(".J_allDown").click(function() {
        var 
            checkedList = [],
            checkedNum = $("input[name='subCheck']:checked").length; 

        $("input[name='subCheck']:checked").each(function() { 
            checkedList.push($(this).parents('tr').attr('data-id')); 
        }); 

        if(checkedNum == 0) { // 判断是否至少选择一项 
            Alert('提示信息', '请至少选择一项!');  
        }else{// 批量选择
            Confirm('提示信息', '确定导出所选问卷吗？', function(){
                $('.J_selectAll').attr('checked',false);
                checkedList = checkedList.toString();
                window.location ='export/'+checkedList; 
            });
        }
    });    
});